const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const logger = require('./logger');

// 确保上传目录存在
const createUploadDir = (dir) => {
  const uploadPath = path.join(process.cwd(), dir);
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
    logger.info(`创建上传目录: ${uploadPath}`);
  }
  return uploadPath;
};

// 配置图片存储
const imageStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = createUploadDir('public/uploads/images');
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueSuffix = uuidv4();
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}-${uniqueSuffix}${ext}`);
  }
});

// 配置文件存储
const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = createUploadDir('public/uploads/files');
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueSuffix = uuidv4();
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}-${uniqueSuffix}${ext}`);
  }
});

// 文件过滤器
const imageFilter = (req, file, cb) => {
  logger.debug('收到上传图片请求:', {
    fieldname: file.fieldname,
    originalname: file.originalname,
    mimetype: file.mimetype,
    size: file.size
  });
  
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    logger.warn(`拒绝上传图片，不支持的类型: ${file.mimetype}`);
    cb(new Error('不支持的图片格式，只支持 JPG, PNG, GIF 和 WEBP 格式'));
  }
};

const fileFilter = (req, file, cb) => {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/plain',
    'application/zip',
    'application/x-rar-compressed'
  ];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件格式'));
  }
};

// 配置上传中间件
const uploadImage = multer({
  storage: imageStorage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制文件大小为 5MB
  },
  fileFilter: imageFilter
});

const uploadFile = multer({
  storage: fileStorage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 限制文件大小为 10MB
  },
  fileFilter: fileFilter
});

module.exports = {
  uploadImage,
  uploadFile
}; 